package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Order;
import cn.wolfcode.domain.Product;
import cn.wolfcode.feign.IProductFeignService;
import cn.wolfcode.mapper.OrderMapper;
import cn.wolfcode.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;

@Service
@RequiredArgsConstructor
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    private final RestTemplate restTemplate;
    private final DiscoveryClient discoveryClient;
    private final IProductFeignService productFeignService;

    @Override
    public Order createOrder(Long pid, Long uid) {
        Order order = new Order();
        //商品
        //方案1：通过restTemplate方式
        // String url = "http://localhost:8081/product/"+pid;
        // Product product = restTemplate.getForObject(url, Product.class);

        //方案2：使用注册中心api方式-discoveryClient
        // List<ServiceInstance> instances = discoveryClient.getInstances("product-service");
        // ServiceInstance instance = instances.get(0);// 当前只有一个
        // String host = instance.getHost();
        // int port = instance.getPort();
        // String url = String.format("http://%s:%d/product/%d",host,port,pid);
        // Product product = restTemplate.getForObject(url, Product.class);

        //方案3：使用注册中心api方式-discoveryClient--带负载均衡
        // List<ServiceInstance> instances = discoveryClient.getInstances("product-service");
        // int index = new Random().nextInt(instances.size());
        // ServiceInstance instance = instances.get(index);
        // String url = String.format("http://%s:%d/product/%d",instance.getHost(),instance.getPort(),pid);
        // Product product = restTemplate.getForObject(url, Product.class);

        //方案4：使用Ribbon方式--带负载均衡
        //String url = String.format("http://product-service/product/%d",pid);
        //Product product = restTemplate.getForObject(url, Product.class);

        // log.info("从nacos中获取的url地址：{}",url);

        //方案5：使用feign接口--带负载均衡
        Product product = productFeignService.get(pid);
        if (product==null){
            throw new RuntimeException("不存在的商品信息");
        }
        order.setPid(pid);
        order.setProductName(product.getName());
        order.setProductPrice(product.getPrice());
        // 用户
        order.setUid(uid);
        order.setUsername("asan");
        order.setNumber(1);
        log.info("订单：{}",order);
        this.save(order);
        return order;
    }
}
